<template>
  <a-modal
    :width="800"
    :visible="true"
    :title="t('指派审核人')"
    :maskClosable="false"
    @ok="submit"
    @cancel="close"
  >
    <div class="p-5">
      <div class="mt-2"
        ><div>{{ title }}{{ t('【当前】：') }}</div>
        <a-input :value="data.currentUserNames" disabled />
      </div>
      <div class="mt-2"
        ><div>{{ title }}{{ t('【指派给】：') }}</div>

        <SelectUser
          :selectedIds="selectedIds"
          :disabledIds="data.currentUserIds"
          :multiple="true"
          @change="getUserList"
        >
          <a-input :value="data.selectedNames" />
        </SelectUser>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive } from 'vue';
  import { getApproveUserList, postSetAssignee } from '/@/api/workflow/task';
  import { SelectUser } from '/@/components/SelectOrganizational/index';
  import { getUserMulti } from '/@/api/system/user';
  import { notification } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const props = defineProps({
    schemaId: {
      type: String,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
    taskId: {
      type: String,
      required: true,
    },
  });
  let emits = defineEmits(['close']);
  let data: {
    currentUserNames: string;
    currentUserIds: Array<string>;
    selectedNames: string;
    selectedList: Array<{ id: string; name: string }>;
  } = reactive({
    selectedList: [],
    currentUserIds: [],
    currentUserNames: '',
    selectedNames: '',
  });
  const selectedIds = computed(() => {
    return data.selectedList.map((ele) => {
      return ele.id;
    });
  });
  onMounted(async () => {
    if (props.schemaId && props.taskId) {
      try {
        let userList = await getApproveUserList(props.schemaId, props.taskId);
        data.currentUserNames = userList
          .map((ele) => {
            return ele.name;
          })
          .join(',');
        data.currentUserIds = userList.map((ele) => {
          return ele.id;
        });
      } catch (_error) {}
    }
  });

  async function getUserList(list: Array<string>) {
    data.selectedList = await getUserMulti(list.join(','));
    data.selectedNames = data.selectedList
      .map((ele) => {
        return ele.name;
      })
      .join(',');
  }
  async function submit() {
    try {
      let res = await postSetAssignee(props.taskId, selectedIds.value);
      if (res) {
        notification.open({
          type: 'success',
          message: t('指派审核人'),
          description: t('指派审核人成功'),
        });
        close();
      } else {
        notification.open({
          type: 'error',
          message: t('指派审核人'),
          description: t('指派审核人失败'),
        });
      }
    } catch (error) {}
  }
  function close() {
    emits('close');
  }
</script>

<style lang="less" scoped></style>
